<?php

namespace App\Admin\Controller\Base;

use App\AbstractController;
use App\Common\Util\TP;
use App\Common\Util\Response;
use App\Common\Util\Response\Json;
use Psr\Http\Message\ResponseInterface;
use Sc\Util\MysqlDataBackup\Backup;
use Sc\Util\MysqlDataBackup\Connect;
use think\annotation\route\Route;
use think\facade\App;

/**
 * 数据备份
 *
 * Class DataBackUpController
 */
class DataBackUpController extends AbstractController
{
    /**
     * 备份
     *
     * @return Json|ResponseInterface|\think\Response
     */
    public function backup(): Json|ResponseInterface|\think\Response
    {
        $database   = TP::config('database.connections.mysql');
        $backupDir  = empty($database['backup']['dir']) ? 'data' : $database['backup']['dir'];
        $backupDir  = strtr(App::getRootPath() . '/' . $backupDir, ['//' => '/']);
        $verifyCode = empty($database['backup']['verifyCode']) ? "AAAAAAAAAA" : $database['backup']['verifyCode'];

        $RConnect = new Connect($database['database'], $database['hostname'], $database['username'], $database['password'], $database['hostport']);
        $backUp   = new Backup($RConnect, $backupDir, md5($verifyCode));
        $result   = $backUp->render(TP::request()->post());

        if (is_string($result)) {
            return Response::html($result);
        }

        return Response::json($result);
    }
}